package copy.controller;

import copy.com.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("/common")
public class ComController {
    @Value("${a.b}")
    private String basePath;

    /**
     * w文件上传
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String oldname = file.getOriginalFilename();
        //截取文件尾部 以 。 切割
        String s = oldname.substring(oldname.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String newname = UUID.randomUUID().toString() + s;
        //确保存入的文件夹存在 无则创建
        File f = new File(basePath);
//        if (f == null) {
        if (!f.exists()) {
            f.mkdirs();
        }
        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + newname));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(newname);
    }

    /**
     * 文件下载
     * 返回值不为void 会报如下错误
     *   No converter for [class copy.com.R] with preset Content-Type 'image/jpeg'
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws Exception {
        //输入流，通过输入流读取文件内容
        try {
            FileInputStream input = new FileInputStream(new File(basePath + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream out = response.getOutputStream();
            //写回去的图片格式数据流
            response.setContentType("image/jpeg");
            int l = 0;
            byte[] bytes = new byte[2048];
            while ((l = input.read(bytes)) != -1) {
                out.write(bytes, 0, l);
                out.flush();
            }
            //关闭资源
            out.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        return R.success("ok");
    }
}










